//
//  OrderPaymentCtr.swift
//  eemall
//
//  Created by zhuxietong on 2018/9/25.
//  Copyright © 2018 zhuxietong. All rights reserved.
//

import UIKit
import soapp
import Eelay
import AsyncDisplayKit
import Photos


public class OrderPaymentCtr: ASListController {
    public var scheme = SaleScheme.normal

    public var sections:TP.section{
        get{
            var addresses = [[String:Any]]()
            var ad_list = DataNode.path(node: "order.verifystores", mo.model, value: NSMutableArray())//v1.0
            if ad_list.count < 1{
                ad_list = DataNode.path(node: "order.verifystores.list", mo.model, value: NSMutableArray())//v1.1
            }
            
            ad_list.list { (obj:NSMutableDictionary, i) in
                if i == 0{
                    addresses.append(
                    ["cellID":"blank","height":"8"]
                    )
                    addresses.append(
                        ["cellID":"title","title":"地址","tag":"更多".loc,"__model":mo.model]
                    )
                }
                obj["cellID"] = "address"
                addresses.append(obj.swift_dictionary)
            }
            
            
            let sec:TP.section = [
                [
                    ["cellID":"code","__model":mo.model],
                ],
                addresses,
                [
                    ["cellID":"log_header","icon":"wddd_rz","title":"订单日志".loc],
                    ["cellID":"logs","__model":mo.model],
                    
                ],
            ]
            return sec
        }
    }
    
    
    public var selector:TP.selector{
        get{
            let sel:TP.selector = [
                "cellID<code>":CodeCell.self,
                "cellID<logs>":ShoppingOrderDetailCtr.LogCell.self,
                "cellID<log_header>":ShoppingOrderDetailCtr.LogHeader.self,
                "cellID<address>":AddressCell.self,
                "cellID<title>":TitleCell.self,
                "cellID<blank>":BlankNode.self,
            ]
            return sel
        }
    }
    
    public var orderID:String{
        get{
            var id = mo.model["order.id",""]
            if id.len < 1
            {
                id = mo.model["id",""]
            }
            return id
        }
    }

    public override func viewDidLoad() {
        super.viewDidLoad()
        tableNode.backgroundColor = UIColor.table_bg_color
        title = "消费码".loc

        refreshView()
        // Do any additional setup after loading the view.
    }
    

    override public func mo_request_send() {
        
        weak var wself = self
        loadingV.loading()
        JoTask().get.log.params(["orderid":orderID])._surl(.订单详情).json_handle { (status, msg, obj, resp) in
            wself?.loadingV.dismiss()
            if status.isSuccess{
                if let dict = obj as? NSMutableDictionary{
                    wself?.mo.model = dict
                    wself?.refreshView()
                    return
                }
            }
            wself?.mo_request_alert(msg: msg, title: "", bt_title: "重试".loc)
            }.run()
    }
    
    func refreshView() {
        tableNode.load(sections: sections, selector: selector)
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
}


extension OrderPaymentCtr{
    
    class TitleCell: JoCellNode {
        let titleL = JoTextNode()
        let moreBt = ASButtonNode()
        override func mo_model_reload() {
            //            separatorTopHeight = 8
            //            separatorTopColor = UIColor.table_bg_color
            separatorHeight = TP.separatorHeight
            separatorColor = UIColor.table_bg_color
            backgroundColor = .white
            moreBt.ui.font(size: 13).ncolor(hex: "#999").ntitle(title: mo.model["tag",""])
            titleL.attributedText = mo.model["title",""].ui.font12.cl_888.astring
            moreBt.addTarget(self, action: #selector(showMore), forControlEvents: .touchUpInside)
        }
        
        @objc func showMore() {
           
            let ctr = OrderOfflineAddress()
            ctr.mo.model = DataNode.path(node: "__model", mo.model, value: NSMutableDictionary())
            mo.controller?.navigationController?.pushViewController(ctr, animated: true)
            
           
        }
        
        override func specGetter() -> _Spec {
            return _Spec.stack(["h|16",[10,AppTheme.edge],_nowrap,&-.center], childs: [
                titleL[_shrink(1),_grow(1)],
                moreBt.Spec
                ])
        }
    }
    
    class AddressCell: JoCellNode {
        
        let storeL = JoTextNode()
        let addressL = JoTextNode()
        let callBt = ASButtonNode()
        
        let line1 = ASDisplayNode()
        let line2 = ASDisplayNode()
        
        override func addLayoutRules() {
            separatorHeight = TP.separatorHeight
            separatorColor = UIColor.table_bg_color
            callBt.addTarget(self, action: #selector(callAction), forControlEvents: .touchUpInside)
        }
        
        @objc func callAction() {
            __app.call(serverPhone: mo.model["tel",__app.serverPhone])
        }
        
        override func mo_model_reload() {
            //            separatorTopHeight = 8
            //            separatorTopColor = UIColor.table_bg_color
            //            separatorHeight = 8
            //            separatorColor = UIColor.table_bg_color
            backgroundColor = .white
            
            line1.backgroundColor = UIColor.separator_color
            line2.backgroundColor = UIColor.separator_color
            let address = mo.model["address",""]
            let name =  mo.model.possible("merchname","storename", default: "线下店".loc)
            storeL.attributedText = name.ui.font12.cl_333.astring
            addressL.attributedText = address.ui.font11.cl_666.astring
            
            _ = callBt.ui.padding(insets: [4,10]).nimage(UIImage(named: "bodadianhua"))
            
        }
        
        override func specGetter() -> _Spec {
            let spec = _Spec.stack([[10,AppTheme.edge],"v|8",&-.stretch], childs: [
                _Spec.stack(["h|16",_nowrap,&-.center], childs: [
                    _Spec.stack(["v|8",_nowrap,&-.stretch,_grow(1),_shrink(1)], childs: [
                        storeL.Spec,
                        addressL.Spec
                        ]),
                    line2[TP.separatorHeight,"\(40)"],
                    callBt.Spec
                    ]),
                ]
            )
            return spec
        }
    }
    
    public class InfoCell:JoCellNode{
        let titleL = UILabel()
    }

    class CodeCell: JoCellNode {
        //二维码
        var QRView = ASImageNode()
        let codeL = JoTextNode()
        let nodeL = JoTextNode()
        
        var status = GoodsVerification.Status.unkown
        
        var statusV = ASImageNode()
        
        var addTap = false
        
        var verification = GoodsVerification(detail: NSMutableDictionary())
        public override func mo_model_reload() {
            
            nodeL.attributedText = "长按或者截图保存二维码，出示给商家".loc.ui.font13.cl_333.center.astring
            backgroundColor = .white
            verification = GoodsVerification(detail: DataNode.path(node: "__model", mo.model, value: NSMutableDictionary()))
            
            status = verification.status
            
            statusV.image = status.code_status_img
            backV.backgroundColor = UIColor(shex: "#fffa")
            
            switch status {
            case .unuse,.used,.timeout:
                backV.backgroundColor = UIColor.clear

                separatorTopHeight = 8
                separatorColor = UIColor.table_bg_color
                separatorHeight = 8
                separatorTopColor = UIColor.table_bg_color
                createQR1()
            default:
                separatorTopHeight = 0
                separatorHeight = 0

                //                spec = _Spec.wrapper(blank[0])
            }
            
            if !addTap
            {
                let tap = UILongPressGestureRecognizer(target: self, action: #selector(longPressed(press:)))
                tap.minimumPressDuration = 1.2
                backV.view.addGestureRecognizer(tap)
            }
            addTap = true
        }
        
        let blank = ASDisplayNode()
        let backV = ASDisplayNode()
        public override func specGetter() -> _Spec {
            
            
            var spec = _Spec.wrapper(blank[0])
            
            
            switch status {
            case .used,.timeout:
                let spec1 = _Spec.stack(["v|10",[10],&-.center], childs: [
                    QRView["\(185.co)",185.co],
                    codeL.Spec,
                    nodeL.Spec,
                    ])
                //                spec = _Spec.back([], over: _Spec.stack([], childs: [
                //                    statusV["60",60],
                //                    ]), back:  spec1)
                
                let back = _Spec.back([], over: _Spec.stack([], childs: [
                    statusV["60",60],
                    ]), back: backV.Spec)
                
                spec = _Spec.over([], over: back, back: spec1)
            case .unuse:
                let spec1 = _Spec.stack(["v|10",[10],&-.center], childs: [
                    QRView["\(185.co)",185.co],
                    codeL.Spec,
                    nodeL.Spec,
                    ])
                //                spec = _Spec.back([], over: _Spec.stack([], childs: [
                //                    statusV["60",60],
                //                    ]), back:  spec1)
                
                let back = _Spec.back([], over: _Spec.stack([], childs: [
                    statusV["60",60],
                    ]), back: backV.Spec)
                
                spec = _Spec.over([], over: back, back: spec1)
//                let spec1 = _Spec.stack(["v|10",[10],&-.center], childs: [
//                    QRView["\(185.co)",185.co],
//                    codeL.Spec,
//                    nodeL.Spec,
//                    ])
//                spec = _Spec.over([], over: _Spec.stack([], childs: [
//                    statusV["60",60],
//                    ]), back: spec1)
            default:
                break
                //                spec = _Spec.wrapper(blank[0])
            }
            
            
            return spec
        }
        
        @objc func longPressed(press:UILongPressGestureRecognizer) {
            if press.state == .began
            {
                saveImage()
            }
        }
        
        @objc func saveImage(){
            let img = QRView.view.shootImage
            
            weak var wself = self
            switch  PHPhotoLibrary.authorizationStatus() {
            case .authorized:
                JoAlertView(info: "提示".loc,"是否确认将二维码保存至我的相册".loc,"取消".loc).append(title: "保存".loc) {
                    PHPhotoLibrary.shared().performChanges({
                        PHAssetChangeRequest.creationRequestForAsset(from: img)
                    }) { (isSuccess: Bool, error: Error?) in
                        if isSuccess {
                            wself?.showMessage(msg: "保存成功".loc)
                        } else{
                            if let _ = error
                            {
                                wself?.showMessage(msg: "保存失败，请重试".loc)
                            }
                            else{
                                wself?.showMessage(msg: "保存失败".loc)
                            }
                        }
                    }
                    }.show(at: self.content_controller)
            case .denied:
                if let url = URL(string: UIApplication.openSettingsURLString)
                {
                    JoAlertView(info: "提示".loc,"您未开启相册访问权限".loc,"取消".loc).append(title: "去设置".loc) {
                        UIApplication.shared.openURL(url)
                        }.show(at: self.content_controller)
                    
                }
            case .restricted:
                
                break
            case .notDetermined:
                PHPhotoLibrary.requestAuthorization { (status) in
                    switch status{
                    case .authorized:
                        wself?.saveImage()
                    case .denied:
                        wself?.showMessage(msg: "保存失败，未能获得相册访问权限".loc)
                    case .restricted:
                        break
                    default:
                        break
                    }
                }
            default:
                break
            }
        }
        
        func showMessage(msg:String) {
            co_delay(delay: 0.01) {
                msg.alert()
            }
        }
        
        public func createQR1()
        {
            // qrView.hidden = false
            // tView.hidden = true
            
            
            
            let code = mo.model["__model.order.verifyinfo.0.verifycode","客户端未获取到验证码".loc]
            codeL.attributedText = "\("编码".loc)：\(code)".ui.font13.center.cl_333.astring
            
            
            let scale = UIScreen.main.scale
            let icon_size = scale * 185.co
            let qrImg = LBXScanWrapper.createCode(codeType: "CIQRCodeGenerator",codeString:code, size: [icon_size,icon_size], qrColor: UIColor.black, bkColor: UIColor.white)
            let logoImg = UIImage(named:"shop_logo") ?? UIImage.image(.clear)
            
            QRView.image = LBXScanWrapper.addImageLogo(srcImg: qrImg!, logoImg: logoImg, logoSize: CGSize(width: 50*scale, height: 50*scale))
            
          
        }
        
    }
    
}


open class OrderOfflineAddress:ASCollectionContainer{
    
    var orderID:String{
        get{
            return self.mo.model.possible("order.id", default: "")
        }
    }
    
    var GoodsID:String{
        get{
            return self.mo.model.possible("list.0.goods.0.goodsid","order.goods.0.goodsid", default: "")
        }
    }
    
    open func create_content(){

        self.page_load_section = "section0"
        self.content = ASTermsContainer.list(
            net: JoTask().post.log._surl(.线下核销地址),
            node: "list",
            emptyMsg: "没有相关内容".loc,
            params: ["orderid":orderID,"goodsid":GoodsID],//v1.0 用orderid,v1.1用goodsid
            cellType: OrderPaymentCtr.AddressCell.self,
            detailType: nil,
            test: false
        )
        
    }
    override open func viewDidLoad() {
        create_content()
        super.viewDidLoad()
        self.title = "可消费门店".loc
        collectionNode.backgroundColor = UIColor.table_bg_color
        reload_page()
        
    }
}
//
//open class OrderOfflineAddressV2:ASCollectionContainer{
//
//    var GoodsID:String{
//        get{
//            return self.mo.model.possible("list.0.goods.0.goodsid","order.goods.0.goodsid", default: "")
//        }
//    }
//
//    open func create_content(){
//        self.page_load_section = "section0"
//        self.content = ASTermsContainer.list(
//            net: JoTask().post.log.log_response()._surl(.线下核销地址),
//            node: "list",
//            emptyMsg: "没有相关内容",
//            params: ["goodsid":GoodsID],
//            cellType: OrderPaymentCtr.AddressCell.self,
//            detailType: nil,
//            test: false
//        )
//    }
//
//    override open func viewDidLoad() {
//        create_content()
//        super.viewDidLoad()
//        self.title = "可消费门店"
//        collectionNode.backgroundColor = UIColor.table_bg_color
//        reload_page()
//
//    }
//}
//
